package xyz.thoughtset.viewer.modules.ds.http.core.req;

import lombok.SneakyThrows;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.http.MediaType;

import java.io.IOException;



public class SyncHttpReq extends BaseReq{

    public SyncHttpReq(boolean wasHttp, String baseUrl, OkHttpClient okHttpClient) {
        super(wasHttp, baseUrl, okHttpClient);
    }


    @Override
    public String doGet(String url,boolean formatUrl) {
        Request request = new Request.Builder()
                .url(buildUrl(url,formatUrl))
                .get()
                .build();
        return exeReq(request);
    }

    @Override
    public String doPost(String url,boolean formatUrl,String jsonStr) {
        RequestBody body = null;
        if (jsonStr != null) {
            body = RequestBody.create(
                    jsonStr,
                    okhttp3.MediaType.parse(MediaType.APPLICATION_JSON_VALUE)
            );
        }
        Request request = new Request.Builder()
                .url(buildUrl(url,formatUrl))
                .post(body) // 这里可以添加请求体
                .build();
        return exeReq(request);
    }

    @SneakyThrows
    private String exeReq(Request request){
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 解析响应
            return response.body().string();
        }
    }


}
